package com.wm.exam.controller;

import com.wm.exam.common.Const;
import com.wm.exam.common.ServerResponse;
import com.wm.exam.pojo.User;
import com.wm.exam.service.HistoryVoService;
import com.wm.exam.service.UserService;
import com.wm.exam.vo.HistoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private HistoryVoService historyVoService;

    @RequestMapping("page/login")
    public String loginPage() {
        return "login";
    }

    /**
     * 用户登录
     */
    @PostMapping("user/login")
    @ResponseBody
    public ServerResponse userLogin(User user, HttpServletRequest request) {
        User nowUser = userService.login(user);
        if (nowUser != null) {
            request.getSession(true).setAttribute(Const.CURRENT_USER, nowUser);
            return ServerResponse.createBySuccess("登录成功", nowUser);
        }
        return ServerResponse.createByErrorMessage("学号或者密码错误");
    }

    /**
     * 用户基本信息界面
     */
    @RequestMapping("page/userInfo")
    public String userInfoPage(HttpServletRequest request, Model model) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return "login";
        }
        // 查询用户的考试记录
        List<HistoryVo> historyVos = historyVoService.getByStuNum(user.getStuNum());
        model.addAttribute("history", historyVos);
        return "info";
    }

}
